package com.kx.hackathon.service.impl;

import com.kx.hackathon.service.HandlerService;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service("CyjlServiceImpl")
public class CyjlServiceImpl implements HandlerService {
    @Autowired
    OkHttpClient httpClient;

    private String check(String word) throws IOException {
        String url = "https://chengyu.qianp.com/cy/"+word;
        System.out.println(url);
        Request request = new Request.Builder()
                .url(url)
                .get()//默认就是GET请求，可以不写
                .build();
        Response response = httpClient.newCall(request).execute();
        if(response.code()==200) {
            String web = response.body().string();
            System.out.println(web);
            jl(word);
            return web;
        }else {
            return "“" + word + "”好像不是个成语哦，请重新接龙。";
        }
    }

    private String jl(String word) throws IOException {
        String url = "https://chengyu.qianp.com/zuci/"+word.charAt(0)+"/1";
        System.out.println(url);
        Request request = new Request.Builder()
                .url(url)
                .get()//默认就是GET请求，可以不写
                .build();
        Response response = httpClient.newCall(request).execute();
        if(response.code()==200) {
            String web = response.body().string();
            System.out.println(web);
            return web;
        } else {
            return "你赢了，这个我还不会接";
        }
    }

    @Override
    public String handle(String msg, String arg) {
        try {
            check(msg);
        } catch (IOException e) {
            return "接龙失败啦";
        }
        return null;
    }

    @Override
    public String init(String msg, String arg) {

        return "欢迎来玩成语接龙，你先说一个成语我来接。";
    }

    @Override
    public boolean needInit() {
        return true;
    }
}
